package com.baosight.risk.service.ridc.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baosight.risk.api.fltd.FlaaNodeAuthoService;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.ridc.RidcRiskService;
import com.baosight.risk.api.workflow.AfterHandler;
import com.baosight.risk.api.workflow.UpdateHandler;
import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.base.entity.MultipleUpdateStatus;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.fltd.FlaaNodeAuthoMapper;
import com.baosight.risk.mapper.fltd.FltdProcessMapper;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.mapper.ridc.RidcRiskAdvanceMapper;
import com.baosight.risk.mapper.ridc.RidcRiskDescMapper;
import com.baosight.risk.mapper.ridc.RidcRiskEvaluateMapper;
import com.baosight.risk.mapper.ridc.RidcRiskEvaluateResultMapper;
import com.baosight.risk.mapper.ridc.RidcRiskMapper;
import com.baosight.risk.mapper.riim.RiimRiskEvaluationMapper;
import com.baosight.risk.mapper.riim.RiimRiskGoalMapper;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.riri.RiriDutyUserMapper;
import com.baosight.risk.mapper.xtdc.XtdcAttachMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.fltd.entity.FltdProcess;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.fltd.vo.NodeTransitionVO;
import com.baosight.risk.service.ridc.entity.RidcRisk;
import com.baosight.risk.service.ridc.entity.RidcRiskAdvance;
import com.baosight.risk.service.ridc.entity.RidcRiskDesc;
import com.baosight.risk.service.ridc.entity.RidcRiskEvaluate;
import com.baosight.risk.service.ridc.entity.RidcRiskEvaluateResult;
import com.baosight.risk.service.ridc.vo.RidcRiskAdvanceVO;
import com.baosight.risk.service.ridc.vo.RidcRiskDescVO;
import com.baosight.risk.service.ridc.vo.RidcRiskEvaluateVO;
import com.baosight.risk.service.ridc.vo.RidcRiskVO;
import com.baosight.risk.service.riim.entity.RiimRiskEvaluation;
import com.baosight.risk.service.riim.entity.RiimRiskGoal;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.riim.vo.RiimRiskImportVO;
import com.baosight.risk.service.riri.entity.RiriDutyUser;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.xtdc.entity.XtdcAttach;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.web.freemarker.FreeMarkerController;

import lombok.extern.slf4j.Slf4j;


/**
 * @author houmingcheng
 * @date 2019.07.05
 */
@Slf4j
@Service
public class RidcRiskServiceImpl extends BaseServiceImpl<RidcRisk> implements RidcRiskService, UpdateHandler, AfterHandler {

    @Autowired
    private FltdProcessMapper processMapper;
    @Autowired
    private RiimRiskImportMapper riimRiskImportMapper;
    @Autowired
    private RidcRiskMapper ridcRiskMapper;
    @Autowired
    private RidcRiskDescMapper ridcRiskDescMapper;
    @Autowired
    private RidcRiskAdvanceMapper ridcRiskAdvanceMapper;
    @Autowired
    private RidcRiskEvaluateMapper ridcRiskEvaluateMapper;
    @Autowired
    private RidcRiskEvaluateResultMapper ridcRiskEvaluateResultMapper;
    @Autowired
    private XtdcAttachMapper xtdcAttachMapper;
    @Autowired
    private RiimRiskGoalMapper riimRiskGoalMapper;
    @Autowired
    private FltdProcessService fltdProcessService;
    @Autowired
    private RiriDutyUserMapper userMapper;
    @Autowired
    private IXtzyCompanyService xtzyCompanyService;
    @Autowired
    private RidcRiskService ridcRiskService;
    @Autowired
    private FreeMarkerController freeMarkerController;
    @Autowired
    private RiimRiskEvaluationMapper evaluationMapper;

    @Autowired
    private XtzyUserMapper xtzyUserMapper;

    @Autowired
    private FltdTaskMapper fltdTaskMapper;

    @Autowired
    private FlaaNodeAuthoMapper flaaNodeAuthoMapper;
    @Autowired
    private FlaaNodeAuthoService flaaNodeAuthoService;

    @Override
    public BaseMapper getMapper() {
        return ridcRiskMapper;
    }


    @Override
    public void saveRidcRisk(RidcRiskVO ridcRiskVO) {
        //获取并保存风险档案
        RidcRisk ridcRisk = ridcRiskVO.getRidcRisk();
        String docRiskId = ridcRisk.getId();
        ridcRisk.setLastUpdateDate(new Date());
        ridcRiskMapper.updateByPrimaryKeySelective(ridcRisk);
        //        //获取并保存风险监督与改进
        List<RidcRiskAdvanceVO> ridcRiskAdvanceVOS = ridcRiskVO.getRidcRiskAdvanceVOS();
        if (CollectionUtils.isNotEmpty(ridcRiskAdvanceVOS)) {
            for (RidcRiskAdvance ridcRiskAdvance : ridcRiskAdvanceVOS) {
                if (StringUtils.isEmpty(ridcRiskAdvance.getId())) {
                    Integer rowOrder;
                    Integer integer = ridcRiskAdvanceMapper.selectMaxRowOrder(ridcRiskAdvance);
                    if (integer == null) {
                        rowOrder = 1;
                    } else {
                        rowOrder = integer + 1;
                    }
                    ridcRiskAdvance = (RidcRiskAdvance) BeanUtils.initBean(ridcRiskAdvance);
                    ridcRiskAdvance.setRowOrder(rowOrder);
                    ridcRiskAdvanceMapper.insert(ridcRiskAdvance);
                } else {
                    BeanUtils.updateBean(ridcRiskAdvance);
                    ridcRiskAdvanceMapper.updateByPrimaryKeySelective(ridcRiskAdvance);
                }
            }
        }
        List<RidcRiskDesc> listA = ridcRiskVO.getRidcRiskDescsA();
        List<RidcRiskDesc> listB = ridcRiskVO.getRidcRiskDescsB();
        List<RidcRiskDesc> listC = ridcRiskVO.getRidcRiskDescsC();
        if (CollectionUtils.isNotEmpty(listA)) {
            for (RidcRiskDesc ra : listA) {
                if (StringUtils.isEmpty(ra.getId())) {
                    Integer rowOrder = null;
                    Integer integer = ridcRiskDescMapper.selectMaxRowOrder(ra);
                    if (integer == null) {
                        rowOrder = 1;
                    } else {
                        rowOrder = integer + 1;
                    }
                    ra = (RidcRiskDesc) BeanUtils.initBean(ra);
                    ra.setRowOrder(rowOrder);
                    ridcRiskDescMapper.insert(ra);
                } else {
                    BeanUtils.updateBean(ra);
                    ridcRiskDescMapper.updateByPrimaryKeySelective(ra);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(listB)) {
            for (RidcRiskDesc ra : listB) {
                if (StringUtils.isEmpty(ra.getId())) {
                    Integer rowOrder = null;
                    Integer integer = ridcRiskDescMapper.selectMaxRowOrder(ra);
                    if (integer == null) {
                        rowOrder = 1;
                    } else {
                        rowOrder = integer + 1;
                    }
                    ra = (RidcRiskDesc) BeanUtils.initBean(ra);
                    ra.setRowOrder(rowOrder);
                    ridcRiskDescMapper.insert(ra);
                } else {
                    BeanUtils.updateBean(ra);
                    ridcRiskDescMapper.updateByPrimaryKeySelective(ra);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(listC)) {
            for (RidcRiskDesc ra : listC) {
                if (StringUtils.isEmpty(ra.getId())) {
                    Integer rowOrder = null;
                    Integer integer = ridcRiskDescMapper.selectMaxRowOrder(ra);
                    if (integer == null) {
                        rowOrder = 1;
                    } else {
                        rowOrder = integer + 1;
                    }
                    ra = (RidcRiskDesc) BeanUtils.initBean(ra);
                    ra.setRowOrder(rowOrder);
                    ridcRiskDescMapper.insert(ra);
                } else {
                    BeanUtils.updateBean(ra);
                    ridcRiskDescMapper.updateByPrimaryKeySelective(ra);
                }
            }
        }
        //获取并保存风险评估
        List<RidcRiskEvaluate> ridcRiskEvaluates = ridcRiskVO.getRidcRiskEvaluates();
        if(ridcRiskEvaluates != null){
            for (RidcRiskEvaluate ridcRiskEvaluate : ridcRiskEvaluates) {
                if (StringUtils.isEmpty(ridcRiskEvaluate.getId())) {
                    Integer rowOrder;
                    Integer integer = ridcRiskEvaluateMapper.selectMaxRowOrder(ridcRiskEvaluate);
                    if (integer == null) {
                        rowOrder = 1;
                    } else {
                        rowOrder = integer + 1;
                    }
                    ridcRiskEvaluate = (RidcRiskEvaluate) BeanUtils.initBean(ridcRiskEvaluate);
                    ridcRiskEvaluate.setRowOrder(rowOrder);
                    ridcRiskEvaluateMapper.insert(ridcRiskEvaluate);
                } else {
                    BeanUtils.updateBean(ridcRiskEvaluate);
                    ridcRiskEvaluateMapper.updateByPrimaryKeySelective(ridcRiskEvaluate);
                }
            }
        }
        //获取并保存自评结论
        RidcRiskEvaluateResult ridcRiskEvaluateResult = ridcRiskVO.getRidcRiskEvaluateResult();
        if (ridcRiskEvaluateResult != null) {
            if (StringUtils.isEmpty(ridcRiskEvaluateResult.getId())) {
                ridcRiskEvaluateResult.setDocRiskId(docRiskId);
                ridcRiskEvaluateResult = (RidcRiskEvaluateResult) BeanUtils.initBean(ridcRiskEvaluateResult);
                ridcRiskEvaluateResultMapper.insert(ridcRiskEvaluateResult);
            } else {
                BeanUtils.updateBean(ridcRiskEvaluateResult);
                ridcRiskEvaluateResultMapper.updateByPrimaryKeySelective(ridcRiskEvaluateResult);
            }
        }
    }

    @Override
    public void addRidcRisk(String jobParam, String jobId,String manageCompCode,String manageCompName) throws Exception {
        //去重发布
        List<RidcRisk> ridcRisks = new ArrayList<>();
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        try {
            String yearQ = "";
            String acctYear = "";
            if (StringUtils.isNotEmpty(jobParam) && jobParam.indexOf(",") > 1) {
                String[] split = jobParam.split(",");
                acctYear = split[0];
                yearQ = acctYear;
            } else {
                acctYear = DateUtils.format(new Date(), "yyyy");
                yearQ = String.valueOf(Integer.valueOf(acctYear) - 1);
            }
            //一些必要的业务信息
            doAddRidcRisk(yearQ,manageCompCode);
            //拼装查询条件
            RidcRisk ridcRisk = new RidcRisk();
            ridcRisk.setAcctYear(yearQ);
            ridcRisk.setManageCompCode(manageCompCode);
            List<RidcRisk> select = ridcRiskMapper.selectList(ridcRisk);
            //补发去重
            for (RidcRisk ridcRisk1 : select) {
                FltdProcess fltdProcess = new FltdProcess();
                fltdProcess.setAcctYear(yearQ);
                if("BGTA".equals(manageCompCode)){
                    fltdProcess.setFlowNo("fengxiandangan");
                }else {
                    fltdProcess.setFlowNo("jididangan");
                }
                fltdProcess.setBizGuid(ridcRisk1.getId());
                List<FltdProcess> select1 = processMapper.select(fltdProcess);
                if (CollectionUtils.isEmpty(select1)) {
                    ridcRisks.add(ridcRisk1);
                }
            }
            FltdTaskVO taskVO = new FltdTaskVO();
            if("BGTA".equals(manageCompCode)){
                taskVO.setFlowNo("fengxiandangan");
                taskVO.setFlowName("重点风险档案");
            }else{
                taskVO.setFlowNo("jididangan");
                taskVO.setFlowName("基地重点风险档案");
            }

            taskVO.setManageCompCode(manageCompCode);
            taskVO.setManageCompName(manageCompName);
            taskVO.setAcctYear(yearQ);
            if (CollectionUtils.isNotEmpty(ridcRisks)) {
                for (RidcRisk rr : ridcRisks) {
                    //根据档案查出来关联的重点风险
                    RiimRiskImport riimRiskImport = new RiimRiskImport();
                    riimRiskImport.setAcctYear(rr.getAcctYear());
                    riimRiskImport.setRiskNo(rr.getRiskNo());
                    riimRiskImport.setManageCompCode(rr.getManageCompCode());
                    RiimRiskImport riimImport1 = riimRiskImportMapper.selectOne(riimRiskImport);
                    //填充工作流需要的数据
                    if (riimImport1 != null) {
                        XtzyCompany company = new XtzyCompany();
                        company.setCompCode(riimImport1.getDeptCode());
                        company.setCompName(riimImport1.getDeptName());
                        taskVO.setCustomCompany(company);
                        taskVO.setCompCode(riimImport1.getCompCode());
                        taskVO.setCompName(riimImport1.getCompName());
                        taskVO.setDeptCode(riimImport1.getDeptCode());
                        taskVO.setDeptName(riimImport1.getDeptName());
                        taskVO.setBizName(riimImport1.getRiskName());
                        String bizDesc = "<" + riimImport1.getRiskName() + ">" + taskVO.getAcctYear() + "年度风险档案";
                        taskVO.setBizDesc(bizDesc);
                        taskVO.setTaskGuid(riimImport1.getId());
                        taskVO.setBizGuid(rr.getId());
                        taskVO.setGroupCondition(taskVO.getAcctYear());
                    }
                    try {
                        //启动流程
                        fltdProcessService.doStart(taskVO);
                        logs.add(fltdProcessService.getLog("重点风险档案-流程启动成功", 0, "业务id：" + rr.getId() + "，重点风险id：" + taskVO.getTaskGuid(), jobId));
                    } catch (Exception e) {
                        logs.add(fltdProcessService.getLog("重点风险档案-流程启动失败", 1, e.getMessage(), jobId));
                        error = e;
                        break;
                    }
                }
            } else {
                logs.add(fltdProcessService.getLog("没有需要下发的重点风险数据", 1, "没有重点风险数据-下发异常", jobId));
            }
        } catch (Exception e) {
            logs.add(fltdProcessService.getLog("重点风险档案-下发异常", 1, e.getMessage(), jobId));
            error = e;
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }
    }

    @Override
    public List<XtzyUser> getUser(Map<String, String> params) {

        String bizGuid = params.get("bizGuid");
        String taskGuid = params.get("taskGuid");
        String bizType = params.get("bizType");
//        String yyyy = DateUtils.format(new Date(), "yyyy");
        //拼装查询条件找出风险档案推进人
        RiriDutyUser ririDutyUser = new RiriDutyUser();
        ririDutyUser.setBizType(bizType);
        ririDutyUser.setBizGuid(bizGuid);
        ririDutyUser.setExt1(taskGuid);
        List<RiriDutyUser> userList = userMapper.select(ririDutyUser);
        //提交推进人给工作流
        List<XtzyUser> xtzyUsers = new ArrayList<>();
        for (RiriDutyUser user : userList) {
            XtzyUser xtzyUser = new XtzyUser();
            xtzyUser.setUserCode(user.getUserCode());
            xtzyUser.setUserDesc(user.getUserDesc());
            xtzyUser.setExt1(user.getCompCode());
            xtzyUser.setExt2(user.getCompName());
            xtzyUsers.add(xtzyUser);
        }
        return xtzyUsers;
    }

    @Override
    public List<RidcRisk> selectListByIds(List<String> ids) {
        return ridcRiskMapper.selectListByIds(ids);
    }

    @Override
    public List<RidcRisk> selectListByDept(RiimRiskImportVO importVO) {
        if (StringUtils.isNotEmpty(importVO.getDeptCode())) {
            List<XtzyCompany> parantAndChildrens = xtzyCompanyService.getParantAndChildrens(importVO.getDeptCode());
            List<String> deptList = parantAndChildrens.stream().map(XtzyCompany::getCompCode).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(deptList)) {
                importVO.setCompIdList(deptList);
            }
        }
        if (CollectionUtils.isNotEmpty(importVO.getCompIdList())) {
            importVO.getCompIdList().add(importVO.getDeptCode());
            importVO.setDeptCode(null);
        }
        List<RidcRisk> ridcRisks = ridcRiskMapper.selectListByDept(importVO);
        return ridcRisks;
    }

    //评估结论排序
    @Override
    public void updateRowOrderDesc(RidcRiskDescVO vo) {
        boolean end = vo.isEnd();
        String sort = vo.getSort();
        RidcRiskDesc ridcRiskDesc = ridcRiskDescMapper.selectByPrimaryKey(vo.getRidcRiskDesc().getId());
        Integer rowOrder = ridcRiskDesc.getRowOrder();
        //待交换对象
        RidcRiskDesc ridcRiskDesc2 = null;
        if (!end) {
            if (rowOrder != null) {
                if ("up".equals(sort)) {
                    //上移
                    ridcRiskDesc2 = ridcRiskDescMapper.selectLess(ridcRiskDesc);
                    if (ridcRiskDesc2 != null) {
                        ridcRiskDesc.setRowOrder(ridcRiskDesc2.getRowOrder());
                        ridcRiskDesc2.setRowOrder(rowOrder);
                        ridcRiskDescMapper.updateByPrimaryKeySelective(ridcRiskDesc);
                        ridcRiskDescMapper.updateByPrimaryKeySelective(ridcRiskDesc2);
                    }
                } else {
                    //下移
                    ridcRiskDesc2 = ridcRiskDescMapper.selectBigger(ridcRiskDesc);
                    if (ridcRiskDesc2 != null) {
                        ridcRiskDesc.setRowOrder(ridcRiskDesc2.getRowOrder());
                        ridcRiskDesc2.setRowOrder(rowOrder);
                        ridcRiskDescMapper.updateByPrimaryKeySelective(ridcRiskDesc);
                        ridcRiskDescMapper.updateByPrimaryKeySelective(ridcRiskDesc2);
                    }
                }
            }
        }
    }

    //监督与改进排序
    @Override
    public void updateRowOrderAdvance(RidcRiskAdvanceVO vo) {
        boolean end = vo.isEnd();
        String sort = vo.getSort();
        RidcRiskAdvance ridcRiskAdvance = ridcRiskAdvanceMapper.selectByPrimaryKey(vo.getRidcRiskAdvance().getId());
        Integer rowOrder = ridcRiskAdvance.getRowOrder();
        //待交换对象
        RidcRiskAdvance ridcRiskAdvance2 = null;
        if (!end) {
            if (rowOrder != null) {
                if ("up".equals(sort)) {
                    //上移
                    ridcRiskAdvance2 = ridcRiskAdvanceMapper.selectLess(ridcRiskAdvance);
                    if (ridcRiskAdvance2 != null) {
                        ridcRiskAdvance.setRowOrder(ridcRiskAdvance2.getRowOrder());
                        ridcRiskAdvance2.setRowOrder(rowOrder);
                        ridcRiskAdvanceMapper.updateByPrimaryKeySelective(ridcRiskAdvance);
                        ridcRiskAdvanceMapper.updateByPrimaryKeySelective(ridcRiskAdvance2);
                    }
                } else {
                    //下移
                    ridcRiskAdvance2 = ridcRiskAdvanceMapper.selectBigger(ridcRiskAdvance);
                    if (ridcRiskAdvance2 != null) {
                        ridcRiskAdvance.setRowOrder(ridcRiskAdvance2.getRowOrder());
                        ridcRiskAdvance2.setRowOrder(rowOrder);
                        ridcRiskAdvanceMapper.updateByPrimaryKeySelective(ridcRiskAdvance);
                        ridcRiskAdvanceMapper.updateByPrimaryKeySelective(ridcRiskAdvance2);
                    }
                }
            }
        }
    }

    //监督与改进排序
    @Override
    public void updateRowOrderEvaluate(RidcRiskEvaluateVO vo) {
        boolean end = vo.isEnd();
        String sort = vo.getSort();
        RidcRiskEvaluate ridcRiskEvaluate = ridcRiskEvaluateMapper.selectByPrimaryKey(vo.getRidcRiskEvaluate().getId());
        Integer rowOrder = ridcRiskEvaluate.getRowOrder();
        //待交换对象
        RidcRiskEvaluate ridcRiskEvaluate2 = null;
        if (!end) {
            if (rowOrder != null) {
                if ("up".equals(sort)) {
                    //上移
                    ridcRiskEvaluate2 = ridcRiskEvaluateMapper.selectLess(ridcRiskEvaluate);
                    if (ridcRiskEvaluate2 != null) {
                        ridcRiskEvaluate.setRowOrder(ridcRiskEvaluate2.getRowOrder());
                        ridcRiskEvaluate2.setRowOrder(rowOrder);
                        ridcRiskEvaluateMapper.updateByPrimaryKeySelective(ridcRiskEvaluate);
                        ridcRiskEvaluateMapper.updateByPrimaryKeySelective(ridcRiskEvaluate2);
                    }
                } else {
                    //下移
                    ridcRiskEvaluate2 = ridcRiskEvaluateMapper.selectBigger(ridcRiskEvaluate);
                    if (ridcRiskEvaluate2 != null) {
                        ridcRiskEvaluate.setRowOrder(ridcRiskEvaluate2.getRowOrder());
                        ridcRiskEvaluate2.setRowOrder(rowOrder);
                        ridcRiskEvaluateMapper.updateByPrimaryKeySelective(ridcRiskEvaluate);
                        ridcRiskEvaluateMapper.updateByPrimaryKeySelective(ridcRiskEvaluate2);
                    }
                }
            }
        }
    }


    @Override
    public List<RidcRisk> selectList(RidcRisk ridcRisk) {

        String status = ridcRisk.getStatus();
        if ("B01".equals(status)) {
            XtzyUser user = ShiroUtils.getUser();
            String userCode = user.getUserCode();
            ridcRisk.setDutyUserCode(userCode);
        }
        if (ridcRisk.getAcctYear() != null) {
            ridcRisk.setAcctYear(ridcRisk.getAcctYear().substring(0, 4));
        }
        return ridcRiskMapper.selectList(ridcRisk);
    }

    @Override
    public RidcRiskVO getRidcRiskDetail(String ridcRiskId) {
        //1、获取风险档案主类
        RidcRiskVO ridcRiskVO = new RidcRiskVO();
        RidcRisk ridcRisk = ridcRiskMapper.selectByPrimaryKey(ridcRiskId);
        ridcRiskVO.setRidcRisk(ridcRisk);
        //2、获取风险描述主表内容
        List<RidcRiskDesc> listA = new ArrayList<>();
        List<RidcRiskDesc> listB = new ArrayList<>();
        List<RidcRiskDesc> listC = new ArrayList<>();
        List<RidcRiskDesc> ridcRiskDescs = ridcRiskDescMapper.getRidcRiskDesc(ridcRiskId);
        if (CollectionUtils.isNotEmpty(ridcRiskDescs)) {
            for (RidcRiskDesc rr : ridcRiskDescs) {
                if ("A".equals(rr.getCatFlag())) {
                    listA.add(rr);
                } else if ("B".equals(rr.getCatFlag())) {
                    listB.add(rr);
                } else {
                    listC.add(rr);
                }
            }
            ridcRiskVO.setRidcRiskDescsA(listA);
            ridcRiskVO.setRidcRiskDescsB(listB);
            ridcRiskVO.setRidcRiskDescsC(listC);
        }

        List<RidcRiskEvaluate> ridcRiskEvaluates = ridcRiskEvaluateMapper.getRidcRiskEvaluateBydocRidcRiskId(ridcRiskId);
        ridcRiskVO.setRidcRiskEvaluates(ridcRiskEvaluates);
        List<RidcRiskAdvance> ridcRiskAdvances = ridcRiskAdvanceMapper.getRidcRiskAdvanceBydocRidcRiskId(ridcRiskId);
        ridcRiskVO.setRidcRiskAdvances(ridcRiskAdvances);
        //拼装ridcRiskEvaluateVO对象===展示附件
        List<RidcRiskAdvanceVO> ridcRiskAdvanceVOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ridcRiskAdvances)) {
            for (RidcRiskAdvance r : ridcRiskAdvances) {
                RidcRiskAdvanceVO ridcRiskAdvanceVO = new RidcRiskAdvanceVO();
                BeanUtils.copyBeanProp(ridcRiskAdvanceVO, r);
                List<RidcRiskAdvanceVO.File> fileList = new ArrayList<>();
                List<XtdcAttach> xtdcAttaches = xtdcAttachMapper.selectBySourceGuid(r.getId());
                //根据监督与改进项的id查找附件名字进行拼装
                if (!CollectionUtils.isEmpty(xtdcAttaches)) {
                    for (XtdcAttach x : xtdcAttaches) {
                        RidcRiskAdvanceVO.File file = ridcRiskAdvanceVO.new File();
                        file.setName(StringUtils.substringAfterLast(x.getFileName(), "_"));
                        //预设为null
                        file.setUrl(null);
                        fileList.add(file);
                    }
                }
                ridcRiskAdvanceVO.setFileList(fileList);
                ridcRiskAdvanceVOS.add(ridcRiskAdvanceVO);
            }
        }
        ridcRiskVO.setRidcRiskAdvanceVOS(ridcRiskAdvanceVOS);
        RidcRiskEvaluateResult ridcRiskEvaluateResult = ridcRiskEvaluateResultMapper.getRidcRiskEvaluateResultBydocRidcRiskId(ridcRiskId);
        if (ridcRiskEvaluateResult == null) {
            ridcRiskEvaluateResult = new RidcRiskEvaluateResult();
        }
        ridcRiskVO.setRidcRiskEvaluateResult(ridcRiskEvaluateResult);
        return ridcRiskVO;
       /* RidcRiskVO ridcRiskVO = new RidcRiskVO();
        RidcRisk ridcRisk = ridcRiskMapper.selectByPrimaryKey(ridcRiskId);
        ridcRiskVO.setRidcRisk(ridcRisk);
        List<RidcRiskDesc> ridcRiskDescs = ridcRiskDescMapper.getRidcRiskDesc(ridcRiskId);
        List<RidcRiskDescVO> listA = new ArrayList<>();
        List<RidcRiskDescVO> listB = new ArrayList<>();
        List<RidcRiskDescVO> listC = new ArrayList<>();
        for (RidcRiskDesc rr : ridcRiskDescs) {
            RidcRiskDescVO ridcVoA = new RidcRiskDescVO();
            RidcRiskDescVO ridcVoB = new RidcRiskDescVO();
            RidcRiskDescVO ridcVoC = new RidcRiskDescVO();
            if ("A".equals(rr.getCatFlag())) {
                ridcVoA.setRidcRiskDesc(rr);
                ridcVoA.setRidcRiskDescs(ridcRiskDescMapper.getRidcRiskDescABC(ridcRiskId, rr.getId()));
                listA.add(ridcVoA);
            } else if ("B".equals(rr.getCatFlag())) {
                ridcVoB.setRidcRiskDesc(rr);
                ridcVoB.setRidcRiskDescs(ridcRiskDescMapper.getRidcRiskDescABC(ridcRiskId, rr.getId()));
                listB.add(ridcVoB);
            } else {
                ridcVoC.setRidcRiskDesc(rr);
                ridcVoC.setRidcRiskDescs(ridcRiskDescMapper.getRidcRiskDescABC(ridcRiskId, rr.getId()));
                listC.add(ridcVoC);
            }
        }
        ridcRiskVO.setRidcRiskDescsA(listA);
        ridcRiskVO.setRidcRiskDescsB(listB);
        ridcRiskVO.setRidcRiskDescsC(listC);

        List<RidcRiskEvaluate> ridcRiskEvaluates = ridcRiskEvaluateMapper.getRidcRiskEvaluateBydocRidcRiskId(ridcRiskId);
        ridcRiskVO.setRidcRiskEvaluates(ridcRiskEvaluates);

        List<RidcRiskAdvance> ridcRiskAdvances = ridcRiskAdvanceMapper.getRidcRiskAdvanceBydocRidcRiskId(ridcRiskId);
        ridcRiskVO.setRidcRiskAdvances(ridcRiskAdvances);

        RidcRiskEvaluateResult ridcRiskEvaluateResult = ridcRiskEvaluateResultMapper.getRidcRiskEvaluateResultBydocRidcRiskId(ridcRiskId);
        ridcRiskVO.setRidcRiskEvaluateResult(ridcRiskEvaluateResult);
*/
    }

    @Override
    public Integer updateStatus(MultipleUpdateStatus multipleUpdateStatus) {
        return ridcRiskMapper.updateStatus(multipleUpdateStatus);
    }

    @Override
    public void saveRidcRiskDesc(RidcRiskDesc ridcRiskDesc) {
        if (StringUtils.isEmpty(ridcRiskDesc.getId())) {
            Integer rowOrder = null;
            Integer integer = ridcRiskDescMapper.selectMaxRowOrder(ridcRiskDesc);
            if (integer == null) {
                rowOrder = 1;
            } else {
                rowOrder = integer + 1;
            }
            ridcRiskDesc = (RidcRiskDesc) BeanUtils.initBean(ridcRiskDesc);
            ridcRiskDesc.setRowOrder(rowOrder);
            ridcRiskDescMapper.insert(ridcRiskDesc);
        } else {
            BeanUtils.updateBean(ridcRiskDesc);
            ridcRiskDescMapper.updateByPrimaryKeySelective(ridcRiskDesc);
        }
    }

    @Override
    public void saveRidcRiskEvaluate(RidcRiskEvaluate ridcRiskEvaluate) {
        if (StringUtils.isEmpty(ridcRiskEvaluate.getId())) {
            Integer rowOrder;
            Integer integer = ridcRiskEvaluateMapper.selectMaxRowOrder(ridcRiskEvaluate);
            if (integer == null) {
                rowOrder = 1;
            } else {
                rowOrder = integer + 1;
            }
            ridcRiskEvaluate = (RidcRiskEvaluate) BeanUtils.initBean(ridcRiskEvaluate);
            ridcRiskEvaluate.setRowOrder(rowOrder);
            ridcRiskEvaluateMapper.insert(ridcRiskEvaluate);

        } else {
            BeanUtils.updateBean(ridcRiskEvaluate);
            ridcRiskEvaluateMapper.updateByPrimaryKeySelective(ridcRiskEvaluate);
        }
    }

    @Override
    public void saveRidcRiskAdvance(RidcRiskAdvance ridcRiskAdvance) {
        if (StringUtils.isEmpty(ridcRiskAdvance.getId())) {
            Integer rowOrder;
            Integer integer = ridcRiskAdvanceMapper.selectMaxRowOrder(ridcRiskAdvance);
            if (integer == null) {
                rowOrder = 1;
            } else {
                rowOrder = integer + 1;
            }
            ridcRiskAdvance = (RidcRiskAdvance) BeanUtils.initBean(ridcRiskAdvance);
            ridcRiskAdvance.setRowOrder(rowOrder);
            ridcRiskAdvanceMapper.insert(ridcRiskAdvance);
        } else {
            BeanUtils.updateBean(ridcRiskAdvance);
            ridcRiskAdvanceMapper.updateByPrimaryKeySelective(ridcRiskAdvance);
        }
    }

    @Override
    public Integer deleteRidcRiskDescByIds(List<String> ids) {
        Integer i = ridcRiskDescMapper.deleteRidcRiskDescByIds(ids);
        return 1;
    }

    @Override
    public Integer deleteRidcRiskEvaByIds(List<String> ids) {
        Integer i = ridcRiskEvaluateMapper.deleteRidcRiskEvaByIds(ids);
        return i;
    }

    @Override
    public Map importWord(String ridcId) {
        //获取准备数据
        Map<String, Object> map = new HashMap<>();
        RidcRiskVO ridcRiskDetail = getRidcRiskDetail(ridcId);
        //主表信息
        RidcRisk ridcRisk = ridcRiskDetail.getRidcRisk();
        List<RidcRiskDesc> ridcRiskDescsA = ridcRiskDetail.getRidcRiskDescsA();
        List<RidcRiskDesc> ridcRiskDescsB = ridcRiskDetail.getRidcRiskDescsB();
        List<RidcRiskDesc> ridcRiskDescsC = ridcRiskDetail.getRidcRiskDescsC();
        List<RidcRiskAdvance> ridcRiskAdvances = ridcRiskDetail.getRidcRiskAdvances();
        //评估
        List<RidcRiskEvaluate> ridcRiskEvaluates = ridcRiskDetail.getRidcRiskEvaluates();
        //评估结论
        RidcRiskEvaluateResult ridcRiskEvaluateResult = ridcRiskDetail.getRidcRiskEvaluateResult();
        String riskProbabilityName = " ";
        String impactDegreeName = " ";
        String assessName = " ";
        String assessDesc = " ";
        if (ridcRiskEvaluateResult != null) {
            riskProbabilityName = ridcRiskEvaluateResult.getRiskProbabilityName();
            impactDegreeName = ridcRiskEvaluateResult.getImpactDegreeName();
            assessName = ridcRiskEvaluateResult.getAssessName();
            assessDesc = ridcRiskEvaluateResult.getAssessDesc();
        }

        String createFormat = DateUtils.format(ridcRisk.getCreateTime(), "yyyy-MM-dd");
        String luFormat = DateUtils.format(ridcRisk.getLastUpdateDate(), "yyyy-MM-dd");

        map.put("compName", StringUtils.isEmpty(ridcRisk.getDeptName()) ? " " : zhaunhuan(ridcRisk.getDeptName()));
        map.put("user", " ");

        map.put("riskName", StringUtils.isEmpty(ridcRisk.getRiskName()) ? " " : zhaunhuan(ridcRisk.getRiskName()));
        map.put("riskTypeName", StringUtils.isEmpty(ridcRisk.getRiskTypeName()) ? " " : zhaunhuan(ridcRisk.getRiskTypeName()));
        map.put("riskNo", StringUtils.isEmpty(ridcRisk.getRiskNo()) ? " " : zhaunhuan(ridcRisk.getRiskNo()));
        map.put("dutyUserName", StringUtils.isEmpty(ridcRisk.getDutyUserName()) ? " " : zhaunhuan(ridcRisk.getDutyUserName()));
        map.put("createTime", StringUtils.isEmpty(createFormat) ? " " : zhaunhuan(createFormat));
        map.put("lastUpdateDate", StringUtils.isEmpty(luFormat) ? " " : zhaunhuan(luFormat));

        //风险评估
        List<Map<String, Object>> listA = new ArrayList<>();
        int ra = 0;
        if (CollectionUtils.isNotEmpty(ridcRiskDescsA)) {
            for (RidcRiskDesc n : ridcRiskDescsA) {
                ++ra;
                Map<String, Object> map1 = new HashMap<>();
                map1.put("riskDesc", StringUtils.isEmpty(n.getDescTypeName()) ? " " : zhaunhuan(n.getDescTypeName()));
                map1.put("descTypeName", StringUtils.isEmpty(n.getRiskDesc()) ? " " : zhaunhuan(n.getRiskDesc()));
                listA.add(map1);
            }
        } else {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("descTypeName", " ");
            map1.put("riskDesc", " ");
            listA.add(map1);
        }
        map.put("listA", listA);
        //风险管理策略和风险解决方案
        int rb = 0;
        List<Map<String, Object>> listB = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ridcRiskDescsB)) {
            for (RidcRiskDesc n : ridcRiskDescsB) {
                ++rb;
                Map<String, Object> map1 = new HashMap<>();
                map1.put("riskDesc", StringUtils.isEmpty(n.getDescTypeName()) ? " " : zhaunhuan(n.getDescTypeName()));
                map1.put("descTypeName", StringUtils.isEmpty(n.getRiskDesc()) ? " " : zhaunhuan(n.getRiskDesc()));
                listB.add(map1);
            }
        } else {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("descTypeName", " ");
            map1.put("riskDesc", " ");
            listB.add(map1);
        }
        map.put("listB", listB);
        //年度自评报告
        List<Map<String, Object>> listC = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ridcRiskDescsC)) {
            for (RidcRiskDesc n : ridcRiskDescsC) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("riskDesc", StringUtils.isEmpty(n.getRiskDesc()) ? " " : zhaunhuan(n.getRiskDesc()));
                map1.put("descTypeName", StringUtils.isEmpty(n.getDescTypeName()) ? " " : zhaunhuan(n.getDescTypeName()));
                listC.add(map1);
            }
        } else {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("descTypeName", " ");
            map1.put("riskDesc", " ");
            listC.add(map1);
        }
        map.put("listC", listC);
        //风险评估
        int re = 0;
        List<Map<String, Object>> listE = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ridcRiskEvaluates)) {
            for (RidcRiskEvaluate rre : ridcRiskEvaluates) {
                ++re;
                Map<String, Object> map1 = new HashMap<>();
                map1.put("index", StringUtils.isEmpty(re + "") ? " " : re + "");
                map1.put("riskName", StringUtils.isEmpty(rre.getRiskName()) ? " " : zhaunhuan(rre.getRiskName()));
                map1.put("riskProbabilityName", StringUtils.isEmpty(rre.getRiskProbabilityName()) ? " " : zhaunhuan(rre.getRiskProbabilityName()));
                map1.put("impactDegreeName", StringUtils.isEmpty(rre.getImpactDegree()) ? " " : zhaunhuan(rre.getImpactDegreeName()));
                listE.add(map1);
            }
        } else {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("index", " ");
            map1.put("riskName", " ");
            map1.put("riskProbabilityName", " ");
            map1.put("impactDegreeName", " ");
            listE.add(map1);
        }
        map.put("listE", listE);
        //(一)	风险发生的可能性
        map.put("rpn0", "极高".equals(riskProbabilityName) ? "极高" : " ");
        map.put("rpn1", "高".equals(riskProbabilityName) ? "高" : " ");
        map.put("rpn2", "中".equals(riskProbabilityName) ? "中" : " ");
        map.put("rpn3", "低".equals(riskProbabilityName) ? "低" : " ");
        map.put("rpn4", "极低".equals(riskProbabilityName) ? "极低" : " ");
        //(二)	风险发生后对经营目标的影响程度
        map.put("idn0", "非常严重".equals(impactDegreeName) ? "非常严重" : " ");
        map.put("idn1", "严重".equals(impactDegreeName) ? "严重" : " ");
        map.put("idn2", "中等".equals(impactDegreeName) ? "中等" : " ");
        map.put("idn3", "较小".equals(impactDegreeName) ? "较小" : " ");
        map.put("idn4", "轻微".equals(impactDegreeName) ? "轻微" : " ");
        //监督与改进
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ridcRiskAdvances)) {
            for (RidcRiskAdvance rra : ridcRiskAdvances) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("quarterName", StringUtils.isEmpty(rra.getQuarterName()) ? " " : zhaunhuan(rra.getQuarterName()));
                map1.put("planDetailDesc", StringUtils.isEmpty(rra.getPlanDetailDesc()) ? " " : zhaunhuan(rra.getPlanDetailDesc()));
                map1.put("finishDesc", StringUtils.isEmpty(rra.getFinishDesc()) ? " " : zhaunhuan(rra.getFinishDesc()));
                mapList.add(map1);
            }
        } else {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("quarterName", " ");
            map1.put("planDetailDesc", " ");
            map1.put("finishDesc", " ");
            mapList.add(map1);
        }
        map.put("listAd", mapList);
        //自评结论
        map.put("assessName", StringUtils.isEmpty(assessName) ? " " : zhaunhuan(assessName));
        map.put("assessDesc", StringUtils.isEmpty(assessDesc) ? " " : zhaunhuan(assessDesc));
        map.put("manageCompName", StringUtils.isEmpty(ridcRisk.getManageCompName()) ? " " : ridcRisk.getManageCompName());
        return map;
    }

    @Override
    public Integer deleteRidcRiskAdByIds(List<String> ids) {
        ridcRiskAdvanceMapper.deleteRidcRiskAdByIds(ids);
        return 1;
    }

    @Override
    public void saveRidcRiskResult(RidcRiskEvaluateResult ridcRiskEvaluateResult) {
        String docRiskId = ridcRiskEvaluateResult.getDocRiskId();
        RidcRiskEvaluateResult ridcRiskEvaluateResult1 = ridcRiskEvaluateResultMapper.getRidcRiskEvaluateResultBydocRidcRiskId(docRiskId);
        if (ridcRiskEvaluateResult1 == null) {
            ridcRiskEvaluateResult = (RidcRiskEvaluateResult) BeanUtils.initBean(ridcRiskEvaluateResult);
            ridcRiskEvaluateResultMapper.insert(ridcRiskEvaluateResult);
        } else {
            BeanUtils.updateBean(ridcRiskEvaluateResult);
            ridcRiskEvaluateResult.setId(ridcRiskEvaluateResult1.getId());
            ridcRiskEvaluateResultMapper.updateByPrimaryKeySelective(ridcRiskEvaluateResult);
        }
    }

    //將上上年度重点风险的实施方案的四季度目标新增到上年度风险档案的监督与改进里面去
    private void tranferGoal(RidcRisk ridcRisk) {
        //获取关联的重点风险f
        RiimRiskImport riimImport = new RiimRiskImport();
        riimImport.setRiskNo(ridcRisk.getRiskNo());
        riimImport.setManageCompCode(ridcRisk.getManageCompCode());
        riimImport.setAcctYear(ridcRisk.getAcctYear());
        RiimRiskImport riimRiskImport = riimRiskImportMapper.selectOne(riimImport);
        if(riimRiskImport==null){
            Integer integer = Integer.valueOf(ridcRisk.getAcctYear());
            String last2 = String.valueOf(integer - 1);
            RiimRiskImport riimImportParam = new RiimRiskImport();
            riimImportParam.setRiskNo(ridcRisk.getRiskNo());
            riimImportParam.setAcctYear(last2);
            riimRiskImport=riimRiskImportMapper.selectOne(riimImport);
        }
        if (riimRiskImport != null){
            //根据重点风险查找实施方案--项目目标
            List<RiimRiskGoal> riimRiskGoals = riimRiskGoalMapper.selectByImportGuid(riimRiskImport.getId());
            //根据重点风险找到风险评估信息
            List<RiimRiskEvaluation> riimRiskEvaluations = evaluationMapper.selectByImportGuid(riimRiskImport.getId());
            if (CollectionUtils.isNotEmpty(riimRiskGoals)) {
                for (RiimRiskGoal riimRiskGoal : riimRiskGoals) {
                    List<RidcRiskAdvance> ridcRiskAdvances = new ArrayList<>();
                    RidcRiskAdvance ridcAdvance1 = new RidcRiskAdvance();
                    RidcRiskAdvance ridcAdvance2 = new RidcRiskAdvance();
                    RidcRiskAdvance ridcAdvance3 = new RidcRiskAdvance();
                    RidcRiskAdvance ridcAdvance4 = new RidcRiskAdvance();
                    ridcAdvance1.setDocRiskId(ridcRisk.getId());
                    ridcAdvance1.setQuarterCode("1");
                    ridcAdvance1.setQuarterName("一季度");
                    ridcAdvance1.setPlanDetailDesc(riimRiskGoal.getGoalFirst());
                    ridcAdvance2.setDocRiskId(ridcRisk.getId());
                    ridcAdvance2.setQuarterCode("2");
                    ridcAdvance2.setQuarterName("二季度");
                    ridcAdvance2.setPlanDetailDesc(riimRiskGoal.getGoalSecond());
                    ridcAdvance3.setDocRiskId(ridcRisk.getId());
                    ridcAdvance3.setQuarterCode("3");
                    ridcAdvance3.setQuarterName("三季度");
                    ridcAdvance3.setPlanDetailDesc(riimRiskGoal.getGoalThird());
                    ridcAdvance4.setDocRiskId(ridcRisk.getId());
                    ridcAdvance4.setQuarterCode("4");
                    ridcAdvance4.setQuarterName("四季度");
                    ridcAdvance4.setPlanDetailDesc(riimRiskGoal.getGoalFour());
                    ridcRiskAdvances.add(ridcAdvance1);
                    ridcRiskAdvances.add(ridcAdvance2);
                    ridcRiskAdvances.add(ridcAdvance3);
                    ridcRiskAdvances.add(ridcAdvance4);
                    ridcRiskAdvances.forEach(ad -> {
                        ad = (RidcRiskAdvance) BeanUtils.initBean(ad);
                        ridcRiskAdvanceMapper.insert(ad);
                    });
                }
            }
            if (CollectionUtils.isNotEmpty(riimRiskEvaluations)) {
                for (RiimRiskEvaluation evaluation : riimRiskEvaluations) {
                    RidcRiskEvaluate evaluate = new RidcRiskEvaluate();
                    evaluate.setRiskName(evaluation.getRiskName());
                    evaluate.setDocRiskId(ridcRisk.getId());
                    evaluate.setRowOrder(evaluation.getRowOrder());
                    evaluate = (RidcRiskEvaluate) BeanUtils.initBean(evaluate);
                    ridcRiskEvaluateMapper.insert(evaluate);
                }
            }
        }

    }

    void doAddRidcRisk(String acctYear,String manageCompCode) {
        //1、查询上年的重点风险添加风险档案 例：今年为2019年，找2018年的重点风险
        Integer integer = Integer.valueOf(acctYear);
        RiimRiskImportVO riimRiskImport = new RiimRiskImportVO();
        riimRiskImport.setAcctYear(acctYear);
        riimRiskImport.setManageCompCode(manageCompCode);
        //专项重点风险为N
        riimRiskImport.setSpecialFlag("N");
        //当年重点风险标识为是
        riimRiskImport.setIsOverTheYears("Y");
        riimRiskImport.setExt1("1");
        List<RiimRiskImport> riimRiskImportList = riimRiskImportMapper.selectList(riimRiskImport);
        List<RiimRiskImport> riimRiskImports = new ArrayList<>();
        //去重添加
        for (RiimRiskImport riskImport : riimRiskImportList) {
            RidcRisk ridcRisk = new RidcRisk();
            ridcRisk.setAcctYear(riskImport.getAcctYear());
            ridcRisk.setManageCompCode(manageCompCode);
            ridcRisk.setRiskNo(riskImport.getRiskNo());
            List<RidcRisk> select = ridcRiskMapper.select(ridcRisk);
            if (CollectionUtils.isEmpty(select)) {
                riimRiskImports.add(riskImport);
            }
        }
        //添加至风险档案
        if (CollectionUtils.isNotEmpty(riimRiskImports)) {
            for (RiimRiskImport ri : riimRiskImports
            ) {
                RidcRisk ridcRisk = new RidcRisk();
                BeanUtils.copyBeanProp(ridcRisk, ri);
                ridcRisk = (RidcRisk) BeanUtils.initBean(ridcRisk);
                ridcRisk.setStatus("B01");
                ridcRisk.setStatusName("待填报");
                ridcRiskMapper.insert(ridcRisk);
                tranferGoal(ridcRisk);

            }
        }
    }

    @Override
    /**
     *      status	当前节点状态
     *      nextStatus	下一节点状态
     *      nextStatusName	下一节点状态名称
     *      acctYear	当前年度
     *      quarterCurrent	当前季度
     *      deptCode	填报人的部门编码
     *      bizGuid 业务id
     *      taskGuid 项目id(重点风险id)
     *tjy
     */
    public boolean updateStatus(Map<String, Object> params) {
        RidcRisk ridcRisk = new RidcRisk();
        XtzyUser sysUser = ShiroUtils.getUser();
        String acctYear = params.get("acctYear").toString();
        String bizGuid = params.get("bizGuid").toString();
        ridcRisk.setId(bizGuid);
        ridcRisk.setStatus(params.get("status").toString());
        //回退使用compCode为查询条件
        if (!"B01".equals(ridcRisk.getStatus())) {
            ridcRisk.setDeptCode(params.get("deptCode").toString());
        }
        //待填报推进人code为查询条件
        else {
            ridcRisk.setDutyUserCode(sysUser.getUserCode());
        }
        String statusName = params.get("nextStatusName").toString();
        String status = params.get("nextStatus").toString();
        //查询出需要修改状态的项
        RidcRisk ridcRisk1 = ridcRiskMapper.selectByPrimaryKey(ridcRisk);
        if (ridcRisk1 != null) {
            ridcRisk1.setStatus(status);
            ridcRisk1.setStatusName(statusName);
//            List<String> ids = select.stream().map(RidcRisk::getId).collect(Collectors.toList());
//            MultipleUpdateStatus multipleUpdateStatus = new MultipleUpdateStatus();
//            multipleUpdateStatus.setIds(ids);
//            multipleUpdateStatus.setStatus(status);
//            multipleUpdateStatus.setStatusName(statusName);
            if (ridcRiskMapper.updateByPrimaryKeySelective(ridcRisk1) > 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean doAfter(Map<String, Object> params) {
//        AsyncManager.me().execute(new TimerTask() {
//            @Override
//            public void run() {
                try {
                    String importId = (String) params.get("bizGuid");
                    String acctYear = (String) params.get("acctYear");
                    Map map = ridcRiskService.importWord(importId);
                    if (map.isEmpty()) {
                        log.error("数据为空！");
                        throw new Exception("数据为空");
                    }
                    String sourceModel = "T_RIDC_RISK_" + acctYear;
                    freeMarkerController.exportPDF(map, "ridcRisk.ftl", "fengxiandangan", importId, sourceModel, true);
                } catch (Exception e) {
                    log.error("生成风险档案pdf异常：" + e.getMessage());
                    return false;
                }
//            }
//        });
        return true;
    }

    public String zhaunhuan(String goal) {
        String result = goal.replaceAll("<", "&lt;");
        String result2 = result.replaceAll(">", "&gt;");
//      String result3 = result2.replaceAll("\'", "&#39;");
        String result4 = result2.replaceAll("\"", "&quot;");
        return result4;
    }

    @Override
    public Map pushArchives(String ridcRiskId) {
        Map returnMap=new HashMap();
        returnMap.put("status","1");
        returnMap.put("msg","推送成功");
        try{
            RidcRisk subEntity=new RidcRisk();
            subEntity.setId(ridcRiskId);
            RidcRisk subArchives =ridcRiskMapper.selectOne(subEntity);
            RiimRiskImport riimRiskImport = new RiimRiskImport();
            riimRiskImport.setAcctYear(subArchives.getAcctYear());
            riimRiskImport.setRiskNo(subArchives.getRiskNo());
            riimRiskImport.setManageCompCode(subArchives.getManageCompCode());
            RiimRiskImport riimImport1 = riimRiskImportMapper.selectOne(riimRiskImport);
            //根据parentId获取上级点位的重点风险
            RiimRiskImport parentRiskImport=new RiimRiskImport();
            parentRiskImport.setId(riimImport1.getParentId());
            RiimRiskImport parentRiskList =riimRiskImportMapper.selectById(parentRiskImport);
            //根据上级单位的风险序号和年度加管理单位查询出对应的上级单位风险档案
            RidcRisk paramRidcRisk=new RidcRisk();
            paramRidcRisk.setRiskNo(parentRiskList.getRiskNo());
            paramRidcRisk.setAcctYear(parentRiskList.getAcctYear());
            paramRidcRisk.setManageCompCode(parentRiskList.getManageCompCode());
            List<RidcRisk> parentArchivesList=ridcRiskMapper.selectList(paramRidcRisk);
            for (RidcRisk parentRiskItem :parentArchivesList){
                if("B01".equals(parentRiskItem.getStatus())){
                    //修改风险档案（T_RIDC_RISK）的维护日期（LAST_UPDATE_DATE）
                    RidcRisk riskParam=new RidcRisk();
                    riskParam.setId(parentRiskItem.getId());
                    riskParam.setLastUpdateDate(new Date());
                    ridcRiskMapper.updateRidcRiskByLastDate(riskParam);

                    this.copyArchivesData(parentRiskItem,subArchives);
                    this.submit(parentRiskItem,parentRiskList);
                }else{
                    returnMap.put("status","0");
                    returnMap.put("msg","宝钢股份重点风险监控报告的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流！");
                }
            }
        }catch (Exception e){
            returnMap.put("status","0");
            returnMap.put("msg","扭转流程异常："+e.getMessage());
        }

        return returnMap;
    }


    public void copyArchivesData(RidcRisk parentEntity,RidcRisk subEntity){
        this.deleteArchivesData(parentEntity.getId());
        //复制风险描述（T_RIDC_RISK_DESC）
        RidcRiskDesc riskDesc=new RidcRiskDesc();
        riskDesc.setDocRiskId(subEntity.getId());
        List<RidcRiskDesc> riskDescList=ridcRiskDescMapper.select(riskDesc);
        for (RidcRiskDesc itemDesc:riskDescList) {
            RidcRiskDesc riskDescEntity=new RidcRiskDesc();
            BeanUtils.copyBeanProp(riskDescEntity,itemDesc);
            BeanUtils.initBean(riskDescEntity);
            riskDescEntity.setDocRiskId(parentEntity.getId());
            ridcRiskDescMapper.insert(riskDescEntity);
        }
        RidcRisk updateRidcRisk=new RidcRisk();
        updateRidcRisk.setId(subEntity.getId());
        updateRidcRisk.setExt5(parentEntity.getId());
        ridcRiskMapper.updateByPrimaryKey(updateRidcRisk);
        //复制风险评估T_RIDC_RISK_EVALUATE
        RidcRiskEvaluate riskEvaluate=new RidcRiskEvaluate();
        riskEvaluate.setDocRiskId(subEntity.getId());
        List<RidcRiskEvaluate> evaluateList=ridcRiskEvaluateMapper.select(riskEvaluate);
        for (RidcRiskEvaluate evaluateItem:evaluateList) {
            RidcRiskEvaluate  riskEvaluateInsert=new RidcRiskEvaluate();
            BeanUtils.copyBeanProp(riskEvaluateInsert,evaluateItem);
            BeanUtils.initBean(riskEvaluateInsert);
            riskEvaluateInsert.setDocRiskId(parentEntity.getId());
            ridcRiskEvaluateMapper.insert(riskEvaluateInsert);
        }
        //复制风险评估结论T_RIDC_RISK_EVALUATE_RESULT
        RidcRiskEvaluateResult riskEvaluateResult=new RidcRiskEvaluateResult();
        riskEvaluateResult.setDocRiskId(subEntity.getId());
        List<RidcRiskEvaluateResult> evaluateResultList=ridcRiskEvaluateResultMapper.select(riskEvaluateResult);
        for (RidcRiskEvaluateResult evaluateResultItem:evaluateResultList) {
            RidcRiskEvaluateResult  evaluateResult=new RidcRiskEvaluateResult();
            BeanUtils.copyBeanProp(evaluateResult,evaluateResultItem);
            BeanUtils.initBean(evaluateResult);
            evaluateResult.setDocRiskId(parentEntity.getId());
            ridcRiskEvaluateResultMapper.insert(evaluateResult);
        }
        //复制监督与改进（T_RIDC_RISK_ADVANCE）
        RidcRiskAdvance riskAdvance=new RidcRiskAdvance();
        riskAdvance.setDocRiskId(subEntity.getId());
        List<RidcRiskAdvance> riskAdvanceList=ridcRiskAdvanceMapper.select(riskAdvance);
        for (RidcRiskAdvance advanceItem:riskAdvanceList) {
            RidcRiskAdvance  riskAdvanceInsert=new RidcRiskAdvance();
            BeanUtils.copyBeanProp(riskAdvanceInsert,advanceItem);
            BeanUtils.initBean(riskAdvanceInsert);
            riskAdvanceInsert.setDocRiskId(parentEntity.getId());
            ridcRiskAdvanceMapper.insert(riskAdvanceInsert);
        }
    }

    public void deleteArchivesData(String docRiskId){
        ridcRiskDescMapper.deleteRidcRiskDescBydocRiskId(docRiskId);
        ridcRiskEvaluateMapper.deleteRidcRiskEvaluateBydocRidcRiskId(docRiskId);
        ridcRiskEvaluateResultMapper.deleteRidcRiskEvaluateResultBydocRidcRiskId(docRiskId);
        ridcRiskAdvanceMapper.deleteRidcRiskAdvanceBydocRiskId(docRiskId);
    }

    private void submit(RidcRisk parentRiskItem, RiimRiskImport parentRiskImport){
        if(StringUtils.isNotEmpty(parentRiskImport.getDutyUserCode())){
            XtzyUser xtzyUser = xtzyUserMapper.selectByName(parentRiskImport.getDutyUserCode());
            FltdTaskVO paramTask=new FltdTaskVO();
            paramTask.setFlowNo("fengxiandangan");
            paramTask.setBizGuid(parentRiskItem.getId());
            paramTask.setNodeCode(parentRiskItem.getStatus());
            paramTask.setStatus("open");
            List<FltdTask> taskList = fltdTaskMapper.selectTaskList(paramTask);
            if(taskList.size()>0){
                FltdTaskVO taskVoParam=new FltdTaskVO();
                BeanUtils.copyBeanProp(taskVoParam, taskList.get(0));
                try {
                    FltdTask updateTask=new FltdTask();
                    updateTask.setTodoGuid(taskVoParam.getTodoGuid());
                    //走绿色通道
                    updateTask.setGreenFlag("G");
                    fltdTaskMapper.updateByPrimaryKeySelective(updateTask);
                    taskVoParam.setGreenFlag("G");

                    //获取下一节点审批人
                    Map<String, Object> resultMap = flaaNodeAuthoService.getNextUser(taskVoParam, xtzyUser);

                    if(resultMap.get("isEnd")!=null && "1".equals(resultMap.get("isEnd").toString())){
                        //查询指定节点的下一个节点及转移路线
                        String processDefId = fltdProcessService.getProcessDefId(taskVoParam.getProcGuid());
                        NodeTransitionVO nextTransition = flaaNodeAuthoMapper.nextOneNodeTransition(processDefId, "submit-G-1");
                        taskVoParam.setSubmitButton(nextTransition);

                        fltdProcessService.doSubmit(xtzyUser,taskVoParam);
                    }

                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
    }
}

